import axios from "axios";

const initChatData = {
    chats:[],
    users:{},
    unread:0,
}

const chatActions = {
    MSG_LIST : "MSG_LIST",
    MSG_RECV : "MSG_RECV",
    MSG_READ : "MSG_READ"
}

export function chatReducer(state=initChatData,action){
    switch(action.type){
        case chatActions.MSG_LIST:
            return {...state,chats:action.payload.chats,users:action.payload.users,unread:action.payload.chats.filter(chat=>!chat.read&&chat.from!==action.payload.fromId).length}
        case chatActions.MSG_RECV:
                return {...state,chats:[...state.chats,action.payload],unread:state.unread+1}
        case chatActions.MSG_READ:
            const {from, readnum} = action.payload;
                return {...state,
                    chats:state.chats.map(chat=>({...chat,read:from===chat.from?true:chat.read})),
                    unread:state.unread-readnum}
        default:
            return state
    }
}

export function initChatListAction(chats,users,fromId){
    return {type:chatActions.MSG_LIST,payload:{chats,users,fromId}}
}

export function resvChat(payload){
    return {type:chatActions.MSG_RECV,payload:payload}
}

/**
 * 标为已读
 */
export function markReadChat(to,from,readnum){
    return {type:chatActions.MSG_READ,payload:{to,from,readnum}}
}

/** 
 * 获取聊天内容
*/
export function getChats(fromId){
    return (dispatch) => {
        axios.get('/chatapi/chatlist').then(res=>{
            if(res.status === 200){
                if(res.data.code===0){
                    dispatch(initChatListAction(res.data.data,res.data.users,fromId));
                }
            }
        });
    }
}
